package loja.converters;

import java.util.Iterator;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

import loja.model.compra.pedido.ItemPedidoCompra;

import org.primefaces.component.picklist.PickList;
import org.primefaces.model.DualListModel;

@FacesConverter(value = "itemPedidoCompraPickListConverter")
public class ItemPedidoCompraPickListConverter implements Converter {

	public ItemPedidoCompraPickListConverter() {

	}

	@SuppressWarnings("rawtypes")
	@Override
	public Object getAsObject(FacesContext arg0, UIComponent arg1,
			String stringItemPedidoCompra) {

		Object ret = null;

		if (arg1 instanceof PickList) {
			Object dualList = ((PickList) arg1).getValue();
			DualListModel dl = (DualListModel) dualList;
			for (Iterator iterator = dl.getSource().iterator(); iterator
					.hasNext();) {
				Object o = iterator.next();
				String id = (new StringBuilder()).append(
						((ItemPedidoCompra) o).getIdItemPedidoCompra())
						.toString();
				if (stringItemPedidoCompra.equals(id)) {
					ret = o;
					break;
				}
			}

			if (ret == null) {
				for (Iterator iterator1 = dl.getTarget().iterator(); iterator1
						.hasNext();) {
					Object o = iterator1.next();
					String id = (new StringBuilder()).append(
							((ItemPedidoCompra) o).getIdItemPedidoCompra())
							.toString();
					if (stringItemPedidoCompra.equals(id)) {
						ret = o;
						break;
					}
				}

			}
		}

		return ret;
	}

	@Override
	public String getAsString(FacesContext arg0, UIComponent arg1,
			Object objItemPedidoCompra) {

		if (objItemPedidoCompra == null)
			return null;
		ItemPedidoCompra itemPedidoCompra = (ItemPedidoCompra) objItemPedidoCompra;
		return String.valueOf(itemPedidoCompra.getIdItemPedidoCompra());
	}
}
